// pages/Comment/Comment.js
import request from '../../utils/request';

Page({
  data: {
    comments: [], // 评论列表
    resourceInfo: {}, // 歌曲/专辑信息
  },

  // 页面加载时初始化
  onLoad(options) {
    const { type = 0, id } = options || {};
    if (!id) return wx.showToast({ title: '参数错误', icon: 'none' });
    
    // 同时获取资源信息和评论
    this.getResourceInfo(type, id);
    this.loadComments(type, id);
  },

  // 获取资源信息（歌曲/专辑名称、封面）
  async getResourceInfo(type, id) {
    const apiMap = {
      0: `/song/detail?ids=${id}`,      // 歌曲
      3: `/album?id=${id}`,             // 专辑
    };
    const url = apiMap[type];
    if (!url) return;

    const res = await request(url);
    const data = type === 0 ? res.songs?.[0] : res.album;
    this.setData({ resourceInfo: data || {} });
  },

  // 加载评论
  async loadComments(type, id) {
    try {
      const res = await request(`/comment/new?type=${type}&id=${id}`);
      const comments = res.data?.comments?.map(item => ({
        avatar: item.user?.avatarUrl,
        nickname: item.user?.nickname || '匿名用户',
        time: this.formatTime(item.time),
        content: item.content
      })) || [];
      
      this.setData({ comments });
    } catch (err) {
      wx.showToast({ title: '加载评论失败', icon: 'none' });
    }
  },

  // 时间格式化 (YYYY-MM-DD)
  formatTime(timestamp) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`;
  }
});